package kotan.util;

import java.util.logging.Logger;

public class ConvertUtil {

    private static final Logger logger = Logger.getLogger(ConvertUtil.class.getName());

    public static Object convert(Object newValue, Object oldValue) {
        if (newValue == null) return null;
        if (oldValue == null) return newValue;
        if (newValue.getClass().equals(oldValue.getClass())) return newValue;
        if (Long.class.isInstance(oldValue)) {
            return convert(newValue, (Long) oldValue);
        } else if (Double.class.isInstance(oldValue)) {
            return convert(newValue, (Double) oldValue);
        } else if (Boolean.class.isInstance(oldValue)) {
            return convert(newValue, (Boolean) oldValue);
        }
        logger.warning("convert failed: " + oldValue + ">" + newValue);
        return oldValue;
    }

    protected static Long convert(Object newValue, Long oldValue) {
        try {
            return Long.valueOf(newValue.toString());
        } catch (NumberFormatException e) {
            logger.fine(e.getMessage());
            return oldValue;
        }
    }

    protected static Double convert(Object newValue, Double oldValue) {
        try {
            return Double.valueOf(newValue.toString());
        } catch (NumberFormatException e) {
            logger.fine(e.getMessage());
            return oldValue;
        }
    }

    protected static Boolean convert(Object newValue, Boolean oldValue) {
        return Boolean.valueOf(newValue.toString());
    }
}
